﻿@page "/fetchdata"

@using Microsoft.AspNetCore.Authorization
@using System.Text.Json

@attribute [Authorize]

<h1>Weather forecast</h1>
<RadzenButton Style="width: 100px; height: 20px" />
<RadzenContextMenu />
<p>This component demonstrates fetching data from the server.</p>

@if (Forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in Forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    [Inject] IWeatherForecastService ForecastService { get; set; }
    [Inject] PersistentComponentState ApplicationState { get; set; }

    private List<WeatherForecast> Forecasts { get; set; }

    protected override async Task OnInitializedAsync()
    {
        ApplicationState.RegisterOnPersisting(PersistForecasts);
        if (!ApplicationState.TryTakeFromJson<List<WeatherForecast>>("fetchdata", out var data))
        {
            Forecasts = await ForecastService.GetForecastAsync();
        }
        else
        {
            Forecasts = data;
        }
    }

    private Task PersistForecasts()
    {
        ApplicationState.PersistAsJson("fetchdata", Forecasts);
        return Task.CompletedTask;
    }
}
